package com.qz;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;

import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ConcurrentRequestTest {

    public static void main(String[] args) {
        String icode = "YZ008";
        String key = "dcdzA5ZEMQuzNnM9m4r0";
        String secret = "cpwwBOm5dOXUCFN8iq1YgrLxRmD9PxC3";

        String data = "{\"deviceId\":\"24B04446\",\"commodityCode\":\"810102410\",\"sn\":\"\"}";
        String nonce = "11231231";

        // 设置并发线程数
        int threadCount = 100; // 增加线程数以模拟高并发
        int requestCount = 1000; // 每个线程发送的请求数量
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);

        // 定义请求任务
        Runnable requestTask = () -> {
            for (int i = 0; i < requestCount; i++) {
                try {
                    JSONObject dataBody = new JSONObject();
                    dataBody.put("key", key);
                    dataBody.put("secret", secret);
                    String timeStamp = String.valueOf(System.currentTimeMillis());
                    dataBody.put("ts", timeStamp);
                    dataBody.put("icode", icode);
                    dataBody.put("dataBody", data);
                    dataBody.put("nonce", nonce);

                    String[] validateArray = new String[]{key, timeStamp, data, nonce};
                    Arrays.sort(validateArray);
                    String digestHex = SecureUtil.hmacSha1(secret).digestHex(ArrayUtil.join(validateArray, ""));
                    dataBody.put("sig", digestHex);

                  //  System.out.println("Request Data: " + dataBody);

                    // 发送请求
                    String response = HttpUtil.post("https://sh.sy.tehst.56luntai.com:18886//dache-wmms-admin/api/common/if", dataBody.toString(), 5 * 1000);

//                    String response = HttpUtil.post("http://127.0.0.1:8080/dache-wmms-admin/api/common/if", dataBody.toString(), 5 * 1000);
                    System.out.println("Response: " + response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        // 提交多个并发请求任务
        for (int i = 0; i < threadCount; i++) {
            executor.submit(requestTask);
        }

        // 关闭线程池
        executor.shutdown();
        try {
            if (!executor.awaitTermination(60, TimeUnit.MINUTES)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }
    }
}
